/*
 * @Date: 2022-03-02 10:32:10
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:备份
 * @LastEditTime: 2022-08-01 17:18:24
 * @FilePath: \server\system\service\DatabackupService\databackup.go
 */

package DatabackupService

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"go2admin_pure/system/common/sysconst"
	"go2admin_pure/system/core/config"
	"go2admin_pure/system/core/db"
	"go2admin_pure/system/core/log"
	"go2admin_pure/system/model/Databackup"
	"go2admin_pure/system/util/sys"
	"github.com/spf13/viper"
)

type DatabackupService struct{}

var dbpath = sys.ExecutePath() + "\\" + strings.TrimRight(config.Instance().DB.DBoutpath, "/")

func (databackupService *DatabackupService) List() []Databackup.Dbconfig {

	files, _ := ioutil.ReadDir(dbpath)
	var data []Databackup.Dbconfig
	for _, f := range files {
		if f.IsDir() {

			v := viper.New()
			c := new(Databackup.Dbconfig)
			//v.SetConfigType()
			v.SetConfigFile(fmt.Sprintf("%s/%s/config.toml", dbpath, f.Name()))
			err := v.ReadInConfig()

			if err != nil {
				log.Write(log.Error, err.Error())
			}
			err = v.Unmarshal(&c)
			if err != nil {
				log.Write(log.Error, err.Error())
			}

			data = append(data, *c)

		}
	}
	return data
}

func (databackupService *DatabackupService) Add(r Databackup.Dbconfig) error {
	//备份系统数据
	if r.Type == "sys" {
		r.Tables = sysconst.SysTables
	} else if r.Type == "emsdata" {
		r.Tables = sysconst.EmsDataTables
	} else if r.Type == "emsconfig" {
		r.Tables = sysconst.EmsConfigTables
	}

	if _, err := db.Export(r.Tables, true, r.Desc, r.Type); err != nil {
		return err
	}

	return nil
}

func (databackupService *DatabackupService) Remove(r Databackup.Dbconfig) error {
	dbdir := fmt.Sprintf("%s/%s", dbpath, r.Name)
	os.RemoveAll(dbdir)
	return nil
}

//恢复
func (databackupService *DatabackupService) Restore(r Databackup.Dbconfig) error {

	dbfile := fmt.Sprintf("%s/%s/%s.sql", dbpath, r.Name, r.Name)
	return db.Import(dbfile)

}
